<template>
  <div>
    <search-form
      :search-config="searchConfig"
      :label-width="150"
      @clear="clearSearch"
      @search="handleSearch"
    />
    <div class="btn-box">
      <div v-if="!showAddBtn && btnList.length">
        <el-button v-for="item in btnList" :key="item.buttonId" size="mini" type="primary" @click="btnClick(item)">{{ item.buttonName }}</el-button>
      </div>
      <div v-if="!showAddBtn && !btnList.length">
        <el-button type="primary" size="mini" @click="showAddBtn = true">新增</el-button>
        <el-button type="primary" size="mini" @click="handleChangeStatus(1)">启用</el-button>
        <el-button type="primary" size="mini" @click="handleChangeStatus(0)">停用</el-button>
        <el-button type="primary" size="mini" @click="handleDel">删除</el-button>
      </div>
      <div v-if="showAddBtn">
        <el-button type="primary" size="mini" @click="handleEdit">增行</el-button>
        <el-button type="primary" size="mini" @click="save">保存</el-button>
        <el-button size="mini" @click="cancel">取消</el-button>
      </div>
    </div>
    <el-table
      ref="marketLevelRecommend"
      v-loading="tableLoading"
      element-loading-text="加载中"
      :data="tableData"
      highlight-current-row
      max-height="400"
      :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
      style="width: 100%; margin-top: 20px"
      @selection-change="selectionChangeHandle"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" width="50" label="序号" />
      <el-table-column prop="marketLevel" label="门店市场层级" min-width="100">
        <template slot-scope="scope">
          <span v-if="!scope.row.editFlag">{{ formaterData(marketLevelList, scope.row.marketLevel) }}</span>
          <c-dict-select v-else v-model="scope.row.marketLevel" dict-type-code="MARKET_LEVEL" placeholder="门店市场层级" @change="changeMarketLevel(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="recommendProgram" label="产品推荐方案" min-width="100">
        <template slot-scope="scope">
          <span v-if="!scope.row.editFlag">{{ formaterData(recommendProgramList, scope.row.recommendProgram) }}</span>
          <c-dict-select v-else v-model="scope.row.recommendProgram" dict-type-code="RECOMMEND_PROGRAM" placeholder="产品推荐方案" @change="changeRecommendProgram(scope.row,scope.$index)" />
        </template>
      </el-table-column>
      <el-table-column prop="enable" label="启用状态" min-width="100">
        <template slot-scope="scope">
          <span>{{ formaterData(enableList, scope.row.enable) }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getDictByPatchType } from '@/api/dataDict'
import { getMarketRecommendData, changeMarketLevelState, saveMarketRecommend, queryBtnList } from '@/api/basicData'
export default {
  name: 'MarketLevelRecommend',
  data() {
    return {
      showAddBtn: false,
      tableLoading: false,
      btnList: [],
      tableData: [],
      recommendProgramList: [],
      marketLevelList: [],
      enableList: [
        { dictName: '启用', dictCode: 1 },
        { dictName: '停用', dictCode: 0 }
      ],
      searchConfig: [
        {
          label: '门店市场层级',
          prop: 'marketLevel',
          type: 'select',
          config: {
            remote: true,
            remoteUrl: `/data-dict/api/v2/dictionary/MARKET_LEVEL?appCode=slm&domainCode=marketing`,
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        },
        {
          label: '产品推荐方案',
          prop: 'recommendProgram',
          type: 'select',
          config: {
            remote: true,
            remoteUrl: `/data-dict/api/v2/dictionary/RECOMMEND_PROGRAM?appCode=slm&domainCode=marketing`,
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        },
        {
          label: '启用状态',
          prop: 'enable',
          type: 'radio',
          value: '1',
          placeholder: '',
          config: {
            selectData: [
              { label: '全部', value: '' },
              { label: '启用', value: '1' },
              { label: '停用', value: '0' }
            ]
          }
        }
      ],
      tableSelected: [],
      otherFilters: [{ 'id': 'enable', 'property': 'enable', 'operator': '=', 'value': '1' }]
      // newTableData: []
    }
  },
  created() {
    const menuCode = this.$route.query.menuCode || 'PC2418323'
    queryBtnList(menuCode, 'default').then(res => {
      if (res.success && res.data && res.data.groovyList && (res.data.groovyList.length || res.data.groupList.length)) {
        this.btnList = [...res.data.groovyList, ...res.data.groupList]
      }
    })
    this.getDictByPatchTypeAll(['MARKET_LEVEL', 'RECOMMEND_PROGRAM']).then(res => {
      this.marketLevelList = res.MARKET_LEVEL
      this.recommendProgramList = res.RECOMMEND_PROGRAM
    })
    this.queryTableData(this.otherFilters)
  },
  activated() {},
  methods: {
    // 搜索
    handleSearch(data) {
      this.otherFilters = [...data.filtersRaw]
      this.queryTableData(this.otherFilters)
    },
    setRowKey() {},
    queryTableData(otherFilters) {
      this.tableLoading = true
      const formData = new FormData()
      formData.append('page', 1)
      formData.append('pageFlag', false)
      formData.append('onlyCountFlag', false)
      formData.append('filtersRaw', JSON.stringify(otherFilters))
      getMarketRecommendData(formData).then(res => {
        if (res.success && res.data && res.data.records) {
          this.tableData = res.data.records
          this.tableData.forEach(item => {
            this.$set(item, 'editFlag', false)
          })
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      if (!arr || !arr.length) return
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    // 选中行
    selectionChangeHandle(rows) {
      this.tableSelected = rows
    },
    // 按钮组
    btnClick(btn) {
      switch (btn.buttonCode) {
        case 'add':
          this.showAddBtn = true
          break
        case 'unable':
          this.handleChangeStatus(0)
          break
        case 'enable':
          this.handleChangeStatus(1)
          break
        case 'del':
          this.handleDel()
          break
        default:
          break
      }
    },
    // 增行
    handleEdit() {
      const obj = {
        marketLevel: '',
        recommendProgram: '',
        enable: 1,
        editFlag: true,
        dr: 0
      }
      this.tableData.unshift(obj)
    },
    // 启用:1/停用:0  state停启用状态
    handleChangeStatus(state) {
      if (!this.tableSelected.length) {
        this.$message.warning(`请选择【${state ? '启用' : '停用'}】项`)
        return
      }
      const tmpArr = this.tableSelected.filter(row => row.enable === state)
      if (tmpArr.length > 0) {
        this.$message.warning(`当前所选分类包含${state ? '启用' : '停用'}状态，请勿重复操作`)
        return
      }
      this.$confirm(`此操作将当前所选数据${state ? '启用' : '停用'},是否继续`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableSelected.forEach(item => {
          item.enable = state
        })
        changeMarketLevelState(this.tableSelected).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '操作成功',
              type: 'success'
            })
            this.queryTableData(this.otherFilters)
          }
        })
      })
    },
    // 删除
    handleDel() {
      if (!this.tableSelected.length) {
        this.$message.warning('请选择【删除】项')
        return
      }
      const flag = this.tableSelected.filter(item => (item.enable === 1 || item.enable === '1'))
      if (flag.length > 0) {
        this.$message.warning('所选数据包含启用状态，不可删除')
        return
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableSelected.forEach(item => { item.dr = 1 })
        changeMarketLevelState(this.tableSelected).then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.queryTableData(this.otherFilters)
          }
        })
      })
    },
    // 选择市场层级
    changeMarketLevel(row) {
      this.$nextTick(() => {
        const marketLevel = row.marketLevel
        const recommendProgram = row.recommendProgram
        const flag = this.tableData.filter(item => ((item.marketLevel.length && item.marketLevel === marketLevel) && (item.recommendProgram.length && item.recommendProgram === recommendProgram)))
        if (flag.length > 1) {
          this.$message.warning(`市场层级${this.formaterData(this.marketLevelList, marketLevel)}对应的推荐方案${this.formaterData(this.recommendProgramList, recommendProgram)}已存在，请重新选择`)
          this.$set(row, 'marketLevel', '')
        }
      })
    },
    // 选择推荐方案
    changeRecommendProgram(row, index) {
      this.$nextTick(() => {
        const marketLevel = row.marketLevel
        const recommendProgram = row.recommendProgram
        const flag = this.tableData.filter(item => ((item.marketLevel.length && item.marketLevel === marketLevel) && (item.recommendProgram.length && item.recommendProgram === recommendProgram)))
        if (flag.length > 1) {
          this.$message.warning(`市场层级${this.formaterData(this.marketLevelList, marketLevel)}对应的推荐方案${this.formaterData(this.recommendProgramList, recommendProgram)}已存在，请重新选择`)
          this.$set(row, 'recommendProgram', '')
        }
      })
    },
    // 取消
    cancel() {
      this.showAddBtn = false
      this.queryTableData(this.otherFilters)
    },
    // 保存
    save() {
      const tmpArr = this.tableData.filter(item => !item.marketLevel || !item.recommendProgram)
      if (tmpArr.length > 0) {
        this.$message.warning('请完善表格数据')
        return
      }
      if (!this.tableData.length) {
        this.$message.warning('请添加表格数据')
        return
      }
      const tableArr = this.tableData.filter(item => !item.id)
      if (!tableArr.length) {
        this.$message.warning('请新增表格数据')
        return
      }
      saveMarketRecommend(tableArr).then(res => {
        if (res.success) {
          this.showAddBtn = false
          this.$message.success('操作成功')
          this.queryTableData(this.otherFilters)
        }
      })
    },
    refreshTable(isInit) {
      this.$refs.marketLevelRecommend.initTableData(isInit ? '' : 'onPage')
    }
  }
}
</script>

<style lang="scss" scoped>
.btn-box{
  margin: 20px 0;
}
/deep/.el-table--mini{
  border: 1px solid #DDDDDD;
}
</style>
